package cn.dyw.cloudmusic.http;

import cn.dyw.cloudmusic.config.ParamsConfig;
import cn.dyw.cloudmusic.utils.AESUtils;
import cn.dyw.cloudmusic.utils.RSAUtils;
import cn.dyw.cloudmusic.http.model.Params;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import org.apache.commons.lang3.RandomStringUtils;

import java.nio.charset.Charset;

/**
 * 评论参数生成
 */
@Log4j
public class InitMusicParams {

    private Params params;

    private String i;

    private String encSecKey;

    public InitMusicParams(Params params) {
        this.params = params;
        this.i = RandomStringUtils.randomAlphanumeric(16);
        try {
            this.encSecKey = RSAUtils.encSecKey(this.i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成post请求
     * @return
     */
    public RequestBody buildRequestBody() throws Exception {
        RequestBody body = new FormBody.Builder(Charset.forName("UTF-8"))
                .add("params", getJsonParams())
                .add("encSecKey", getEncSecKey())
                .build();
        return body;
    }

    /**
     * 生成aes加密后的params
     * @return aes加密后的params
     * @throws Exception 加密失败
     */
    public String getJsonParams() throws Exception {
        log.debug("请求参数：" + getParamsToJson());
        String temp = AESUtils.AESEncode(ParamsConfig.g, ParamsConfig.iv, getParamsToJson());
        return AESUtils.AESEncode(i, ParamsConfig.iv, temp);
    }

    public String getEncSecKey() {
        return encSecKey;
    }

    private String getParamsToJson() {
        return JSON.toJSONString(params);
    }

    public Params getParams() {
        return params;
    }

    public String createRequestUrl() {
        return params.requestUrl();
    }
}
